package algorithm_demo.leetcode;

/**
 * 14. 最长公共前缀
 * <a href="https://leetcode.cn/problems/longest-common-prefix/">https://leetcode.cn/problems/longest-common-prefix/</a>
 * @author Api
 * @date 2023/5/9 1:16
 */
public class Problem_014_LongestCommonPrefix {
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0){
            return "";
        }
        String prefix = strs[0];//默认第一个单词为最长公共前缀
        for(int i = 1; i< strs.length;i++){
           while(strs[i].indexOf(prefix) != 0){//只有indexOf=0,才说明是公共前缀
               prefix = prefix.substring(0, prefix.length()-1);//每次去除末尾的字符
               if (prefix.isEmpty()){
                   return "";
               }
           }
        }
        return prefix;
    }
}
